import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.compress.utils.Charsets;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.event.SimpleEvent;
import org.apache.flume.interceptor.Interceptor;
import org.junit.Test;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// 优化策略：可以在采集数据时，拦截器将日志信息中不需要的信息删除掉，仅保留必要的信息。

public class LogTypeInterceptor implements Interceptor {


    @Override
    public void initialize() {

    }

    @Override
    public Event intercept(Event event) {

        String eventBody = new String(event.getBody(), Charsets.UTF_8);

        Map<String, String> headers = event.getHeaders();

        String[] bodyArr = eventBody.split("\\s+");

        try{

            String jsonStr = bodyArr[6];

            String timestampStr = "";
            JSONObject jsonObject = JSON.parseObject(jsonStr);

            if(headers.getOrDefault("logtype", "").equals("start")){

                timestampStr = jsonObject.getJSONObject("app_active").getString("time");
            }else if(headers.getOrDefault("logtype", "").equals("event")){
                JSONArray jsonArray = jsonObject.getJSONArray("lagou_event");
                if(jsonArray.size()>0){
                    timestampStr = jsonArray.getJSONObject(0).getString("time");
                }
            }

            long timestamp = Long.parseLong(timestampStr);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

            Instant instant = Instant.ofEpochMilli(timestamp);
            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
            String date = formatter.format(localDateTime);

            headers.put("logtime", date);
            event.setHeaders(headers);
        }catch (Exception e){
            return null;
        }
        return event;

    }

    @Override
    public List<Event> intercept(List<Event> list) {

        List<Event> events = new ArrayList<>();

        for (Event event : list) {

            Event newEvent = intercept(event);

            if(null!=newEvent){

                events.add(newEvent);
            }
        }

        return events;

    }

    @Override
    public void close() {

    }

    public static class Builder implements Interceptor.Builder{

        @Override
        public Interceptor build() {

            return new cn.lagou.dw.flume.interceptor.LogTypeInterceptor();
        }

        @Override
        public void configure(Context context) {

        }
    }
}
